

import type { SFCDescriptor } from "@vue/compiler-sfc";
import { parse } from "@vue/compiler-sfc";
import MagicString from 'magic-string';
import type { Unimport } from 'unimport';
import { createUnimport } from 'unimport';

export class Parser {
  public unimport!:Unimport
  private descriptor!:SFCDescriptor
  public autoAddImport!:string
  public isImport!:boolean
  

  constructor(public readonly code:string){}

  public parseCode(code:string){
    const {descriptor} = parse(code)
    this.descriptor = descriptor
  }

  public async createUnImport(declaration:string){
    const unimport = createUnimport({
      imports: [{ name: 'default', as: '$dialog', from: declaration+'/index' }],
    })
    this.unimport = unimport
  }

  public async isUnImport():Promise<void>{
    const re = await this.unimport.injectImports(this.code)

    this.isImport = re.imports.length > 0
    this.autoAddImport = re.code
  }


  public importMoundle(code:string):string{
    const s = new MagicString(code)
    const {source} = this.descriptor
    s.replace(source,'')
    return s.toString()
  }

  public transformer(code:string,importCode:string):string{
    const s = new MagicString(code)

    const {scriptSetup} = this.descriptor

    const translate = scriptSetup?.content ?? ''

    s.replace(translate,'\n'+importCode.toString()+translate )

    return s.toString()
  }
}